Error Handling এবং Exception Management

Java Technologies - স্প্রিং বুট ক্লায়েন্ট (Spring Boot Client)
86
86

Spring Boot WebClient-এ Error Handling এবং Exception Management অত্যন্ত গুরুত্বপূর্ণ, কারণ এটি HTTP রিকোয়েস্ট এবং রেসপন্সের সময় সম্ভাব্য ত্রুটি পরিচালনার একটি কার্যকর পদ্ধতি প্রদান করে। এখানে বিস্তারিতভাবে WebClient-এর মাধ্যমে Error Handling এবং Exception Management কিভাবে করা যায় তা উদাহরণসহ আলোচনা করা হলো।


১. Error Handling-এর ধাপসমূহ

  1. HTTP স্ট্যাটাস কোড অনুযায়ী ত্রুটি পরিচালনা।
  2. Custom Exception তৈরি করা।
  3. onStatus() মেথড ব্যবহার করে কাস্টম লজিক।
  4. Global Exception Handling (Spring Boot Controller Advice)

২. HTTP Status Code অনুযায়ী ত্রুটি পরিচালনা

onStatus() মেথড ব্যবহার:

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public class WebClientErrorHandling {

    private final WebClient webClient;

    public WebClientErrorHandling(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchData() {
        return webClient.get()
                .uri("/data")
                .retrieve()
                .onStatus(
                        status -> status.is4xxClientError(), // 4xx ত্রুটি
                        response -> Mono.error(new RuntimeException("Client Error: " + response.statusCode()))
                )
                .onStatus(
                        status -> status.is5xxServerError(), // 5xx ত্রুটি
                        response -> Mono.error(new RuntimeException("Server Error: " + response.statusCode()))
                )
                .bodyToMono(String.class)
                .block();
    }

    public static void main(String[] args) {
        WebClient webClient = WebClient.builder().baseUrl("https://api.example.com").build();
        WebClientErrorHandling example = new WebClientErrorHandling(webClient);

        try {
            String response = example.fetchData();
            System.out.println("Response: " + response);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
        }
    }
}

৩. Custom Exception ব্যবহার

Custom Exception ক্লাস তৈরি:

public class CustomClientException extends RuntimeException {
    public CustomClientException(String message) {
        super(message);
    }
}

public class CustomServerException extends RuntimeException {
    public CustomServerException(String message) {
        super(message);
    }
}

Custom Exception-এর মাধ্যমে Error Handling:

public String fetchDataWithCustomException() {
    return webClient.get()
            .uri("/data")
            .retrieve()
            .onStatus(
                    status -> status.is4xxClientError(),
                    response -> Mono.error(new CustomClientException("Client Error: " + response.statusCode()))
            )
            .onStatus(
                    status -> status.is5xxServerError(),
                    response -> Mono.error(new CustomServerException("Server Error: " + response.statusCode()))
            )
            .bodyToMono(String.class)
            .block();
}

৪. Global Exception Handling (Controller Advice)

Spring Boot-এ @ControllerAdvice ব্যবহার করে সকল Controller-এর জন্য Global Exception Handling করা যায়।

Exception Handler তৈরি:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomClientException.class)
    public String handleClientException(CustomClientException ex) {
        return "Client Error: " + ex.getMessage();
    }

    @ExceptionHandler(CustomServerException.class)
    public String handleServerException(CustomServerException ex) {
        return "Server Error: " + ex.getMessage();
    }

    @ExceptionHandler(Exception.class)
    public String handleGenericException(Exception ex) {
        return "An unexpected error occurred: " + ex.getMessage();
    }
}

৫. Fallback এবং Default Response

Fallback ব্যবহারের মাধ্যমে Default Response প্রদান:

public String fetchDataWithFallback() {
    return webClient.get()
            .uri("/data")
            .retrieve()
            .onStatus(
                    status -> status.is4xxClientError(),
                    response -> Mono.error(new CustomClientException("Client Error"))
            )
            .onStatus(
                    status -> status.is5xxServerError(),
                    response -> Mono.error(new CustomServerException("Server Error"))
            )
            .bodyToMono(String.class)
            .onErrorResume(e -> {
                System.err.println("Error occurred: " + e.getMessage());
                return Mono.just("Default Response");
            })
            .block();
}

৬. Reactive Error Handling (Flux/Mono)

Mono-এর মধ্যে Error Management:

webClient.get()
        .uri("/data")
        .retrieve()
        .bodyToMono(String.class)
        .doOnError(e -> System.err.println("Error occurred: " + e.getMessage()))
        .onErrorReturn("Default Response")
        .block();

Flux-এর ক্ষেত্রে:

webClient.get()
        .uri("/data-stream")
        .retrieve()
        .bodyToFlux(String.class)
        .doOnError(e -> System.err.println("Error occurred: " + e.getMessage()))
        .onErrorResume(e -> Flux.just("Fallback Data"))
        .subscribe(data -> System.out.println("Received: " + data));

৭. Timeout Handling

Timeout সেটআপের মাধ্যমে ত্রুটি পরিচালনা:

WebClient webClient = WebClient.builder()
        .baseUrl("https://api.example.com")
        .build();

String response = webClient.get()
        .uri("/data")
        .retrieve()
        .bodyToMono(String.class)
        .timeout(Duration.ofSeconds(3)) // 3 সেকেন্ডের সময়সীমা
        .onErrorReturn("Request Timed Out")
        .block();

৮. Logging এবং Debugging

Error Handling-এর সময় লগিং খুবই গুরুত্বপূর্ণ। application.properties ফাইলের মাধ্যমে লগিং সক্রিয় করুন:

logging.level.org.springframework.web.reactive.function.client=DEBUG

৯. Error Handling-এর সেরা অনুশীলন

  1. Custom Exception ব্যবহার করুন।
  2. Proper Logging নিশ্চিত করুন।
  3. Fallback Mechanism সেট করুন।
  4. Timeout এবং Retry কনফিগার করুন।
  5. Global Exception Handler দিয়ে কোড পরিচ্ছন্ন রাখুন।

উদাহরণঃ সম্পূর্ণ কোড

@RestController
public class WebClientController {

    private final WebClient webClient;

    public WebClientController(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("https://api.example.com").build();
    }

    @GetMapping("/fetch-data")
    public String fetchData() {
        return webClient.get()
                .uri("/data")
                .retrieve()
                .onStatus(
                        status -> status.is4xxClientError(),
                        response -> Mono.error(new CustomClientException("Client Error"))
                )
                .onStatus(
                        status -> status.is5xxServerError(),
                        response -> Mono.error(new CustomServerException("Server Error"))
                )
                .bodyToMono(String.class)
                .onErrorReturn("Default Response")
                .block();
    }
}

এইভাবে, WebClient-এ Error Handling এবং Exception Management আরও সহজ এবং কার্যকর হয়।

Content added By

RestTemplate এবং WebClient এ Error Handling

119
119

REST API কলের সময় বিভিন্ন ধরনের সমস্যা হতে পারে (যেমন: 4xx বা 5xx HTTP স্ট্যাটাস কোড)। RestTemplate এবং WebClient উভয়ের মধ্যে এসব সমস্যার সমাধান করার জন্য error handling কৌশল প্রয়োগ করা যায়।


RestTemplate-এ Error Handling

১. Default Error Handling:

RestTemplate-এর ডিফল্ট error handling ResponseErrorHandler দ্বারা পরিচালিত হয়।

Custom ResponseErrorHandler তৈরি:

আপনার নিজস্ব ResponseErrorHandler তৈরি করতে পারেন।

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import java.io.IOException;

public class CustomResponseErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return response.getStatusCode().isError();
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        // Custom Error Logic
        if (response.getStatusCode().is4xxClientError()) {
            throw new RuntimeException("Client Error: " + response.getStatusCode());
        } else if (response.getStatusCode().is5xxServerError()) {
            throw new RuntimeException("Server Error: " + response.getStatusCode());
        }
    }
}

RestTemplate-এ Custom Error Handler যুক্ত করা:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new CustomResponseErrorHandler());
        return restTemplate;
    }
}

২. Exception Handling with RestTemplate:

যদি ডিফল্ট বা কাস্টম ErrorHandler ব্যবহার করতে না চান, তাহলে Exception Handling ব্যবহার করতে পারেন।

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@RestController
public class RestTemplateController {

    private final RestTemplate restTemplate;

    public RestTemplateController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/get-data")
    public String getData() {
        String url = "https://example.com/api";

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (HttpClientErrorException e) {
            // Handle 4xx errors
            return "Client Error: " + e.getStatusCode();
        } catch (HttpServerErrorException e) {
            // Handle 5xx errors
            return "Server Error: " + e.getStatusCode();
        } catch (Exception e) {
            // Handle other errors
            return "Unknown Error: " + e.getMessage();
        }
    }
}

WebClient-এ Error Handling

WebClient Reactive Programming এবং Non-blocking কাজ করার জন্য উন্নত error handling পদ্ধতি প্রদান করে। এটি onStatus এবং doOnError এর মতো মেথড ব্যবহার করে।


১. onStatus দিয়ে Error Handling:

Example:

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

@RestController
public class WebClientController {

    private final WebClient webClient;

    public WebClientController(WebClient webClient) {
        this.webClient = webClient;
    }

    @GetMapping("/webclient-error")
    public Mono<String> handleError() {
        return webClient.get()
                .uri("/api/data")
                .retrieve()
                .onStatus(
                        status -> status.is4xxClientError(),
                        response -> Mono.error(new RuntimeException("Client Error!"))
                )
                .onStatus(
                        status -> status.is5xxServerError(),
                        response -> Mono.error(new RuntimeException("Server Error!"))
                )
                .bodyToMono(String.class);
    }
}

২. doOnError দিয়ে Error Logging:

doOnError ব্যবহার করে লগিং বা অতিরিক্ত কাজ করতে পারেন।

Example:

@GetMapping("/webclient-log-error")
public Mono<String> logError() {
    return webClient.get()
            .uri("/api/data")
            .retrieve()
            .bodyToMono(String.class)
            .doOnError(e -> {
                System.err.println("Error occurred: " + e.getMessage());
            })
            .onErrorResume(e -> Mono.just("Fallback Response"));
}

৩. Global Error Handling:

Custom Error Handler তৈরি:

import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

public class CustomWebClientErrorHandler {

    public static Mono<Throwable> handleError(ClientResponse response) {
        if (response.statusCode().is4xxClientError()) {
            return Mono.error(new WebClientResponseException("Client Error", response.rawStatusCode(),
                    response.statusCode().toString(), null, null, null));
        } else if (response.statusCode().is5xxServerError()) {
            return Mono.error(new WebClientResponseException("Server Error", response.rawStatusCode(),
                    response.statusCode().toString(), null, null, null));
        }
        return Mono.error(new RuntimeException("Unknown Error"));
    }
}

WebClient-এ যুক্ত করা:

@GetMapping("/webclient-global-error")
public Mono<String> globalErrorHandler() {
    return webClient.get()
            .uri("/api/data")
            .exchangeToMono(response -> {
                if (response.statusCode().isError()) {
                    return CustomWebClientErrorHandler.handleError(response);
                }
                return response.bodyToMono(String.class);
            });
}

৪. Retry এবং Fallback:

Retry Logic যোগ করা:

@GetMapping("/webclient-retry")
public Mono<String> retryRequest() {
    return webClient.get()
            .uri("/api/data")
            .retrieve()
            .bodyToMono(String.class)
            .retry(3) // 3 বার রিট্রাই করবে
            .onErrorResume(e -> Mono.just("Fallback Response"));
}

RestTemplate বনাম WebClient-এ Error Handling:

বৈশিষ্ট্যRestTemplateWebClient
Default Error HandlingResponseErrorHandleronStatus()
Custom LogicException Handling, Custom ErrorHandlerReactive Error Handling
Reactive Supportনেই (Blocking I/O)আছে (Non-blocking I/O)
Retry এবং FallbackManual Logic প্রয়োজনসরাসরি Retry এবং Fallback যুক্ত করা যায়

উপসংহার:

  • RestTemplate ব্যবহার করলে ResponseErrorHandler ব্যবহার করে error handle করুন।
  • WebClient ব্যবহার করলে onStatus, doOnError এবং onErrorResume এর মতো মেথড ব্যবহার করে error handle করুন।
  • Reactive Programming-এর জন্য WebClient আরও কার্যকর এবং আধুনিক।

প্রয়োজনে আরও উদাহরণ বা ব্যাখ্যা চাইলে জানাতে পারেন! 😊

Content added By

HTTP Status Code এবং Exception Handling কৌশল

87
87

Spring Boot-এ REST API-এর মাধ্যমে HTTP স্ট্যাটাস কোড হ্যান্ডল এবং এক্সেপশন ম্যানেজ করার জন্য বিভিন্ন কৌশল রয়েছে। RestTemplate বা WebClient উভয়ের ক্ষেত্রেই নির্দিষ্ট কৌশল প্রয়োগ করা হয়।


HTTP Status Code এবং Exception Handling কেন গুরুত্বপূর্ণ?

  1. API রেসপন্স যাচাই করা:
    • ক্লায়েন্ট সঠিকভাবে জানবে যে সার্ভার রিকোয়েস্ট সফলভাবে হ্যান্ডেল করেছে কি না।
    • উদাহরণ: 200 OK, 201 Created, 404 Not Found, 500 Internal Server Error
  2. এক্সেপশন ম্যানেজ করা:
    • রিকোয়েস্ট ফেল হলে এর কারণ অনুসারে এক্সেপশন থ্রো এবং হ্যান্ডেল করা প্রয়োজন।

HTTP Status Code এর ধরন

১. 2xx (Success):

সফল রিকোয়েস্ট এবং রেসপন্স নির্দেশ করে।

  • 200 OK
  • 201 Created

২. 4xx (Client Errors):

ক্লায়েন্ট সাইড সমস্যার জন্য ব্যবহার হয়।

  • 400 Bad Request
  • 401 Unauthorized
  • 404 Not Found

৩. 5xx (Server Errors):

সার্ভার সাইড সমস্যার জন্য ব্যবহার হয়।

  • 500 Internal Server Error
  • 503 Service Unavailable

RestTemplate: Exception Handling

RestTemplate-এ Custom Exception এবং HTTP Status Code হ্যান্ডল করার জন্য ResponseErrorHandler ব্যবহার করা হয়।

Custom ResponseErrorHandler তৈরি:

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CustomResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode().is4xxClientError()) {
            // 4xx Errors
            throw new RuntimeException("Client Error: " + response.getStatusCode());
        } else if (response.getStatusCode().is5xxServerError()) {
            // 5xx Errors
            throw new RuntimeException("Server Error: " + response.getStatusCode());
        }
    }
}

RestTemplate-এ Custom Error Handler সেট করা:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    private final CustomResponseErrorHandler errorHandler;

    public RestTemplateConfig(CustomResponseErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(errorHandler); // Custom Error Handler সেট করা
        return restTemplate;
    }
}

RestTemplate-এ Exception Handling উদাহরণ:

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData(String url) {
        try {
            return restTemplate.getForObject(url, String.class);
        } catch (RuntimeException e) {
            System.err.println("Error occurred: " + e.getMessage());
            throw e; // Exception পুনরায় থ্রো করা
        }
    }
}

WebClient: Exception Handling

WebClient-এ HTTP Status Code এবং Exception Handling করার জন্য onStatus এবং onError ব্যবহার করা হয়।

Exception Handling কৌশল:

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchData(String url) {
        try {
            return webClient.get()
                    .uri(url)
                    .retrieve()
                    .onStatus(
                        status -> status.is4xxClientError(), // 4xx Errors হ্যান্ডল করা
                        clientResponse -> Mono.error(new RuntimeException("Client Error"))
                    )
                    .onStatus(
                        status -> status.is5xxServerError(), // 5xx Errors হ্যান্ডল করা
                        clientResponse -> Mono.error(new RuntimeException("Server Error"))
                    )
                    .bodyToMono(String.class)
                    .block();
        } catch (WebClientResponseException e) {
            System.err.println("Error response: " + e.getStatusCode());
            throw e;
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            throw e;
        }
    }
}

Global Exception Handling

Spring Boot-এ Global Exception Handler ব্যবহার করে এক্সেপশন হ্যান্ডল করা যায়। এটি সব API কলের জন্য প্রযোজ্য।

@RestControllerAdvice ব্যবহার:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Error: " + ex.getMessage());
    }

    @ExceptionHandler(WebClientResponseException.class)
    public ResponseEntity<String> handleWebClientResponseException(WebClientResponseException ex) {
        return ResponseEntity
                .status(ex.getStatusCode())
                .body("WebClient Error: " + ex.getMessage());
    }
}

Exception Logging

Spring Boot-এ এক্সেপশন লগ করার জন্য Logger ব্যবহার করা যেতে পারে:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ApiService {

    private static final Logger logger = LoggerFactory.getLogger(ApiService.class);
    private final WebClient webClient;

    public ApiService(WebClient webClient) {
        this.webClient = webClient;
    }

    public String fetchData(String url) {
        try {
            return webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
        } catch (Exception e) {
            logger.error("Error fetching data: ", e);
            throw e;
        }
    }
}

উপসংহার

  1. RestTemplate এবং WebClient-এ এক্সেপশন হ্যান্ডল করা সহজ এবং কাস্টমাইজ করা যায়।
  2. Global Exception Handling ব্যবহার করে সব রিকোয়েস্টের জন্য একই রকম লজিক প্রয়োগ করা যায়।
  3. HTTP Status Code অনুযায়ী বিভিন্ন এক্সেপশন থ্রো করা ক্লায়েন্ট-সার্ভার যোগাযোগের ত্রুটি শনাক্তে সাহায্য করে।
  4. WebClient আধুনিক এবং নন-ব্লকিং হওয়ায় বড় স্কেল অ্যাপ্লিকেশনের জন্য বেশি কার্যকর।

এই কৌশলগুলো ব্যবহার করে আপনি একটি রিলায়েবল এবং ইফিশিয়েন্ট ক্লায়েন্ট তৈরি করতে পারবেন।

Content added By

Custom Exception তৈরি এবং হ্যান্ডল করা

67
67

স্প্রিং বুটে কাস্টম এক্সেপশন তৈরি এবং হ্যান্ডল করার মাধ্যমে API কলের সময় এরর ম্যানেজমেন্ট আরও কার্যকর করা যায়। নিচে ধাপে ধাপে প্রক্রিয়াটি দেখানো হলো:


১. Custom Exception তৈরি করা

কাস্টম এক্সেপশন তৈরি করতে একটি ক্লাস তৈরি করুন যা RuntimeException বা Exception এক্সটেন্ড করে।

উদাহরণ:

public class CustomClientException extends RuntimeException {
    private int statusCode;

    public CustomClientException(String message, int statusCode) {
        super(message);
        this.statusCode = statusCode;
    }

    public int getStatusCode() {
        return statusCode;
    }
}

২. RestTemplate এর জন্য Exception Handling যুক্ত করা

RestTemplate এর সাথে ResponseErrorHandler ব্যবহার করে হ্যান্ডলিং সেটআপ করা যায়।

উদাহরণ:

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;

@Component
public class CustomResponseErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return response.getStatusCode().isError();
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        // Convert error response to custom exception
        throw new CustomClientException("Error occurred: " + response.getStatusText(), response.getStatusCode().value());
    }
}

৩. RestTemplate এর সাথে Custom Error Handler কনফিগার করা

Custom Error Handler যুক্ত করতে RestTemplate বীন কনফিগার করুন।

উদাহরণ:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    private final CustomResponseErrorHandler errorHandler;

    public AppConfig(CustomResponseErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(errorHandler);
        return restTemplate;
    }
}

৪. Exception Handling যুক্ত করে API কল করা

API কল করার সময় কাস্টম এক্সেপশন হ্যান্ডল করতে try-catch ব্লক ব্যবহার করুন।

উদাহরণ:

import org.springframework.stereotype.Service;

@Service
public class ApiService {
    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData(String url) {
        try {
            return restTemplate.getForObject(url, String.class);
        } catch (CustomClientException ex) {
            System.err.println("Custom Exception: " + ex.getMessage() + ", Status Code: " + ex.getStatusCode());
            return "Error occurred while fetching data.";
        }
    }
}

৫. Controller Advice দিয়ে Global Exception Handling

স্প্রিং বুটে গ্লোবাল এক্সেপশন হ্যান্ডলিং করতে @ControllerAdvice ব্যবহার করতে পারেন।

উদাহরণ:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomClientException.class)
    public ResponseEntity<String> handleCustomClientException(CustomClientException ex) {
        return ResponseEntity
                .status(ex.getStatusCode())
                .body("Custom Error: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception ex) {
        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("An unexpected error occurred: " + ex.getMessage());
    }
}

৬. ব্যবহার এবং ফলাফল

API কল করার সময় যদি সার্ভার কোনো এরর রেসপন্স করে, CustomResponseErrorHandler সেই এরর ক্যাপচার করবে এবং কাস্টম এক্সেপশন থ্রো করবে।

উদাহরণ:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Client {
    @Autowired
    private ApiService apiService;

    public void fetchDataExample() {
        String url = "http://example.com/api/resource";
        String response = apiService.fetchData(url);
        System.out.println("Response: " + response);
    }
}

এরর রেসপন্স:

  • যদি সার্ভার থেকে 404 Not Found আসে:

    Custom Exception: Error occurred: Not Found, Status Code: 404
    
  • গ্লোবাল হ্যান্ডলিং (Controller Advice) থাকলে কাস্টম রেসপন্স রিটার্ন করবে:

    {
      "status": 404,
      "message": "Custom Error: Error occurred: Not Found"
    }
    

সংক্ষেপে:

  1. Custom Exception: RuntimeException থেকে এক্সটেন্ড করুন।
  2. ResponseErrorHandler: RestTemplate এর এরর হ্যান্ডলিং সেটআপ করুন।
  3. Global Exception Handling: @ControllerAdvice দিয়ে গ্লোবাল লেভেলে হ্যান্ডল করুন।
  4. Usage: API কলের সময় try-catch দিয়ে সুনির্দিষ্ট হ্যান্ডলিং করুন।

এইভাবে আপনি স্প্রিং বুট ক্লায়েন্টে কাস্টম এক্সেপশন তৈরি এবং পরিচালনা করতে পারবেন।

Content added By

উদাহরণ সহ Exception Handling

69
69

Spring Boot WebClient বা RestTemplate ব্যবহার করে API-তে রিকোয়েস্ট পাঠানোর সময় বিভিন্ন ধরনের সমস্যা দেখা দিতে পারে, যেমন Timeout, Invalid Response, Authentication Failure, ইত্যাদি। এই সমস্যাগুলো মোকাবিলা করার জন্য Exception Handling একটি অপরিহার্য বিষয়। নিচে Spring Boot Client এর মাধ্যমে Exception Handling এর উদাহরণ দেখানো হয়েছে।


Exception Handling এর প্রয়োজনীয় ধাপ:

  1. Custom Exception তৈরি করুন।
  2. WebClient বা RestTemplate এর জন্য Exception Handling যুক্ত করুন।
  3. Globally Exception Handle করার জন্য @ControllerAdvice ব্যবহার করুন।

১. Custom Exception তৈরি করা

public class ApiException extends RuntimeException {
    public ApiException(String message) {
        super(message);
    }
}

২. WebClient ব্যবহার করে Exception Handling

WebClient এর মাধ্যমে API কল এবং Exception Handling:

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;

@Service
public class ApiService {

    private final WebClient webClient;

    public ApiService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("https://api.example.com").build();
    }

    public String fetchData() {
        try {
            return webClient.get()
                    .uri("/data")
                    .retrieve()
                    .onStatus(
                            status -> status.is4xxClientError() || status.is5xxServerError(),
                            response -> {
                                String errorMessage = "Error: " + response.statusCode();
                                return response.bodyToMono(String.class)
                                        .map(body -> new ApiException(errorMessage + " - " + body));
                            }
                    )
                    .bodyToMono(String.class)
                    .block(); // Blocking for simplicity (avoid in production)
        } catch (WebClientResponseException ex) {
            throw new ApiException("WebClient Response Error: " + ex.getMessage());
        } catch (Exception ex) {
            throw new ApiException("An unexpected error occurred: " + ex.getMessage());
        }
    }
}

৩. RestTemplate ব্যবহার করে Exception Handling

RestTemplate এর মাধ্যমে API কল এবং Exception Handling:

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {

    private final RestTemplate restTemplate;

    public RestTemplateService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData() {
        String url = "https://api.example.com/data";
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return response.getBody();
        } catch (HttpClientErrorException | HttpServerErrorException ex) {
            throw new ApiException("RestTemplate Error: " + ex.getStatusCode() + " - " + ex.getResponseBodyAsString());
        } catch (Exception ex) {
            throw new ApiException("An unexpected error occurred: " + ex.getMessage());
        }
    }
}

৪. Global Exception Handling

Spring Boot-এ @ControllerAdvice ব্যবহার করে Exception Handling কে কেন্দ্রীয়ভাবে পরিচালনা করা যায়।

Global Exception Handler:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ApiException.class)
    public ResponseEntity<String> handleApiException(ApiException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception ex) {
        return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

৫. Example Execution

API Call Example:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements CommandLineRunner {

    private final ApiService apiService;

    public AppRunner(ApiService apiService) {
        this.apiService = apiService;
    }

    @Override
    public void run(String... args) {
        try {
            String response = apiService.fetchData();
            System.out.println("API Response: " + response);
        } catch (ApiException ex) {
            System.err.println("Handled Exception: " + ex.getMessage());
        }
    }
}

৬. উদাহরণ রেসপন্স

Success Response:

{
  "data": "This is the API response."
}

Error Response (Handled by Exception Handler):

{
  "error": "RestTemplate Error: 404 NOT_FOUND - Resource not found"
}

Exception Handling Best Practices:

  1. Custom Exception ব্যবহার করুন: প্রজেক্টের মধ্যে স্পষ্ট বার্তা দিতে কাস্টম এক্সসেপশন ব্যবহার করুন।
  2. Proper HTTP Status Return করুন: কনজিউমারদের জন্য উপযুক্ত HTTP স্ট্যাটাস কোড ব্যবহার করুন।
  3. Global Handling: @ControllerAdvice ব্যবহার করে অ্যাপ্লিকেশনের প্রতিটি এক্সসেপশন এক জায়গায় ম্যানেজ করুন।
  4. Reactive Handling: WebClient ব্যবহার করলে Non-blocking Exception Handling ব্যবহার করুন।

এভাবে Exception Handling ইমপ্লিমেন্ট করে আপনি API এর ত্রুটিগুলো আরও সহজে এবং কার্যকরভাবে পরিচালনা করতে পারবেন।

Content added By
টপ রেটেড অ্যাপ

স্যাট অ্যাকাডেমী অ্যাপ

আমাদের অল-ইন-ওয়ান মোবাইল অ্যাপের মাধ্যমে সীমাহীন শেখার সুযোগ উপভোগ করুন।

ভিডিও
লাইভ ক্লাস
এক্সাম
ডাউনলোড করুন
Promotion